package com.hooda.container;

import com.hooda.server.RequestProcessor;

import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Service {

    private ThreadPoolExecutor executor = null;

    private List<Connector> connectors = new ArrayList<>();

    private Engine engine = null;

    public Service() {
    }

    public void addConnector(Connector connector) {
        connectors.add(connector);
    }

    public void setEngine(Engine engine) {
        this.engine = engine;
    }

    public void receive(Socket socket) {
        RequestProcessor processor = new RequestProcessor(socket, engine);
        executor.execute(processor);
    }

    public void init() {
        executor = new ThreadPoolExecutor(10, 50, 100L, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(50), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());

        for (Connector connector : connectors) {
            connector.init();
        }
    }

    public void start() {
        for (Connector connector : connectors) {
            executor.execute(connector);
        }
    }

    public void destroy() {
        for (Connector connector : connectors) {
            connector.destroy();
        }
    }

}
